package dao.impl;

import dao.QuestionDao;
import entiy.Question;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class QuestionDaoImpl extends Questionutil implements QuestionDao {

    @Override
    public List<Question> selectQuestion() {
        List<Question>list=new ArrayList<>();
        String sql="select * from question";
        rs=this.getResultSet(sql,null);
        try {
            while (rs.next()){
                Question question=new Question();
                question.setId(rs.getInt("id"));
                question.setTitle(rs.getString("title"));
                question.setDescription(rs.getString("description"));
                question.setCreatetime(rs.getDate("createtime"));
                question.setAnswercount(rs.getInt("answercount"));
                list.add(question);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeAll();
        }

        return list;
    }

    @Override
    public int add(Question q) {
        String sql="insert into question(title,description,createtime,answercount) values(?,?,?,?)";
        int i=this.executeUpdate(sql,new Object[]{q.getTitle(),q.getDescription(),q.getCreatetime(),q.getAnswercount()});
        return i;
    }

    @Override
    public int deleteQuestion(int id) {
        String sql="delete from question where id=?";
        int i=this.executeUpdate(sql,new Object[]{id});
        return i;
    }

    @Override
    public Question selectbyidQuestion(int id) {
        Question question=null;
        String sql="select * from question where id=?";
        rs=this.getResultSet(sql,new Object[]{id});
        try {
            while (rs.next()){
                question.setTitle(rs.getString("title"));
                question.setDescription(rs.getString("description"));
                question.setCreatetime(rs.getDate("createtime"));
                question.setAnswercount(rs.getInt("answercount"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeAll();
        }
        return question;
    }

    @Override
    public int updateQuestion(Question q) {
        String sql="update question set title=?,description=?,createtime=?,answercount=? where id=?";
        int i=this.executeUpdate(sql,new Object[]{q.getTitle(),q.getDescription(),q.getCreatetime(),q.getAnswercount(),q.getId()});
        return i;
    }
}
